package shuai.biz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import shuai.util.OutOfStockException;

@Component
@Aspect
public class LogAspectBean {
	@Before("execution(* shuai.biz.*.*(..))")
	public void before(JoinPoint jp){
		Object[] args=jp.getArgs();
		String methodName=jp.getSignature().getName();//方法名
		if("buyPhone".equals(methodName)){
			System.out.println("日志"+currTime()+"，即将进行进货操作，进货数量为"+args[0]+"部");
		}
		if("salePhone".equals(methodName)){
			System.out.println("日志"+currTime()+"，即将进行销售操作，销售数量为"+args[0]+"部");
		}
	}
	@AfterReturning("execution(* shuai.biz.*.*(..))")
	public void afterReturning(JoinPoint jp){
		String methodName=jp.getSignature().getName();
		if("buyPhone".equals(methodName)){
			System.out.println("日志"+currTime()+"，进货执行完毕");
		}
		if("salePhone".equals(methodName)){
			System.out.println("日志"+currTime()+"，销售执行完毕");
		}
	}
	
	@AfterThrowing(pointcut="execution(* shuai.biz.*.*(..))",throwing="e")
	public void afterThrowing(JoinPoint jp,OutOfStockException e){
		String methodName=jp.getSignature().getName();
		System.out.println("在"+currTime()+","+methodName+"发生异常"+e.getMessage());
		
	}
	@After("execution(* shuai.biz.*.*(..))")
	public void after(JoinPoint jp){
		String methodName=jp.getSignature().getName();
		if("buyPhone".equals(methodName)){
			System.out.println("日志"+currTime()+"，进货执行完毕,发生异常也要执行");
		}
		if("salePhone".equals(methodName)){
			System.out.println("日志"+currTime()+"，销售执行完毕，发生异常也要执行");
		}
	}
	@Around("execution(* shuai.biz.*.*(..))")
	public Object aroundTest(ProceedingJoinPoint pjp){
		String methodName=pjp.getSignature().getName();
		long start=System.currentTimeMillis();
		System.out.println(methodName+"方法开始执行");
		try{
			return pjp.proceed();
		}catch (Throwable e) {
			e.printStackTrace();
		}finally {
			long end=System.currentTimeMillis();
			System.out.println(methodName+"方法执行完毕，耗时"+(end-start));
		}
		return null;
	}
	
	public String currTime(){
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		return simpleDateFormat.format(new Date());
	}
}
